#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>
#include <mqueue.h>

#include "config.h"
#include "balr_decision_err.h"

#define BUFFER_SIZE sizeof(MSG_decisionErreur)+256

void* BALRdecisionErr()
{
	// Initialisation -----------------------------------------------
	mqd_t queue_decisionErreur;
	int reading_size;
	MSG_decisionErreur msg;

	// opening "BAL_decisionErreur", READ only
	queue_decisionErreur = mq_open(BAL_decisionErreur, O_RDONLY);
	if(queue_decisionErreur == -1)
	{
		perror("[BALR_DecisionErr] Error opening BAL_decisionErreur:");
		return 1;
	}

	// memory initialisation
	//memset(buffer, 0, BUFFER_SIZE); 



	// Running loop -------------------------------------------------

	for(;;)
	{
		// waiting for a msg
		reading_size = mq_receive(queue_decisionErreur, (const char *)&msg, sizeof(MSG_decisionErreur), NULL);

		if(reading_size == -1)
		{
			perror("[BAL_Decision_Erreur] Failed to receive msg from BAL_decisionErreur:");
		}
		else
		{
			// Reading the msg
			//MSG_decisionErreur* msg = (MSG_decisionErreur *) buffer;
			int decision = msg.reponse;
			if(decision == FIN_APPLI)
			{
				printf("[BAL_Decision_Erreur] Received decision from operator:\nStop production\n\n");
			}
			else
			{
				printf("[BAL_Decision_Erreur] Received decision from operator:\nResume production\n\n");
			}
		}
	}
	mq_close(queue_decisionErreur);
}
